package cn.edu.hit.core.combine;

import cn.edu.hit.core.transfer.Transfer;
import cn.edu.hit.core.transfer.TransferLoader;
import cn.edu.hit.core.Document;

import java.lang.reflect.Array;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 展开后求值
 * 如: [[55.59439564327069],[83.8979041722205],[37.28872212923427],[25.117321026634155]]   1to1
 */
public class FlatMapAdapter extends CombineAdapterHelper {
    @Override
    public boolean accept(String type) {
        return "flatMap".equalsIgnoreCase(type);
    }

    @Override
    protected Object combineAndCalculate(List<Document> channelDocs, Document configure, String method, Map<String, Object> arg) {
//        List<Object> channelValues = channelDocs.stream().map(doc->doc.get(VALUE)).collect(Collectors.toList());
        List channelValues = channelDocs.stream()
                .map(doc -> doc.get(VALUE))
                .flatMap(obj -> {
                    if (obj == null) return Stream.<Object>empty();
                    if (obj instanceof Array) return Stream.<Object>of((Object[]) obj);
                    if (obj instanceof Collection) return ((Collection<Object>) obj).stream();
                    return Stream.of(obj);
                })
                .collect(Collectors.toList());
        Transfer transfer = TransferLoader.get(method);
        return transfer.transfer(channelValues, configure);
    }
}
